<template>
	<view class="nc-info-container">
		<uni-nav-bar left-icon="back" shadow="false" status-bar="true" fixed="true" :title="customNavTitle" @click-left="NavReturn"></uni-nav-bar>
		<view v-if="indent == 'all'" class="info-wrap">
			<navigator class="info-list-cell m-t b-b" url="/pages/member/modify_face/modify_face" hover-class="cell-hover">
				<text class="cell-tit">头像</text>
				<view class="info-list-head cell-tip">
					<image :src="memberInfo.user_headimg ? $util.img(memberInfo.user_headimg) : $util.img('upload/uniapp/default_head.png')" mode="aspectFill"></image>
				</view>
				<text class="cell-more"></text>
			</navigator>
			<view class="info-list-cell b-b" hover-class="cell-hover">
				<text class="cell-tit">账号</text>
				<text class="cell-tip">{{ formData.number }}</text>
			</view>
			<view class="info-list-cell b-b" hover-class="cell-hover" @click="modifyInfo('name')">
				<text class="cell-tit">昵称</text>
				<text class="cell-tip">{{ formData.nickName }}</text>
				<text class="cell-more"></text>
			</view>
			<view class="info-list-cell" hover-class="cell-hover" @click="modifyInfo('password')">
				<text class="cell-tit">密码</text>
				<text class="cell-tip">修改</text>
				<text class="cell-more"></text>
			</view>

			<view class="info-list-cell m-t b-b" @click="modifyInfo('mobile')">
				<text class="cell-tit">手机</text>
				<text v-if="formData.user_tel == ''" class="cell-tip">绑定手机号</text>
				<text v-else class="cell-tip">{{ formData.mobile }}</text>
				<text class="cell-more"></text>
			</view>
			<view class="info-list-cell b-b" hover-class="cell-hover" @click="modifyInfo('mailBox')">
				<text class="cell-tit">邮箱</text>
				<text v-if="formData.user_email == ''" class="cell-tip">绑定邮箱</text>
				<text v-else class="cell-tip">{{ formData.email }}</text>
				<text class="cell-more"></text>
			</view>
			<!-- <view class="info-list-cell" hover-class="cell-hover">
				<text class="cell-tit">关联账号</text>
				<text class="cell-more"></text>
			</view> -->
			<view class="info-list-cell log-out-btn" @click="logout"><text class="cell-tit ns-text-color">退出登录</text></view>
		</view>
		<!-- 修改昵称 -->
		<view v-if="indent == 'name'" class="edit-info">
			<view class="edit-info-box">
				<text class="info-name">昵称</text>
				<input class="uni-input info-content input-len" type="text" maxlength="30" placeholder="请输入新昵称" v-model="formData.nickName" />
			</view>
			<view class="info-list-cell log-out-btn" @click="save('name')"><text class="cell-tit ns-text-color">保存</text></view>
		</view>
		<!-- 修改密码 -->
		<view v-if="indent == 'password'" class="edit-info">
			<view class="edit-info-box">
				<text class="info-name">当前密码</text>
				<input class="uni-input info-content input-len" type="password" maxlength="30" placeholder="请输入密码" v-model="formData.currentPassword" />
			</view>
			<view class="edit-info-box">
				<text class="info-name">新密码</text>
				<input class="uni-input info-content input-len" type="password" maxlength="30" placeholder="新密码" v-model="formData.newPassword" />
			</view>
			<view class="edit-info-box">
				<text class="info-name">确认新密码</text>
				<input class="uni-input info-content input-len" type="password" maxlength="30" placeholder="确认新密码" v-model="formData.confirmPassword" />
			</view>
			<view class="info-list-cell log-out-btn" @click="save('password')"><text class="cell-tit ns-text-color">保存</text></view>
		</view>
		<!-- 修改手机号 -->
		<view v-if="indent == 'mobile'" class="edit-info">
			<view class="edit-info-box">
				<text class="info-name">手机号</text>
				<input class="uni-input info-content" type="number" maxlength="11" placeholder="请输入手机号" v-model="formData.mobile" />
			</view>
			<view class="edit-info-box">
				<text class="info-name">验证码</text>
				<input class="uni-input info-content" type="number" maxlength="4" placeholder="请输入验证码" v-model="formData.mobileVercode" />
				<view class="vercode"><imgcode width="80" height="22" ref="imgcode"></imgcode></view>
			</view>
			<view class="edit-info-box">
				<text class="info-name">动态码</text>
				<input class="uni-input info-content" type="number" maxlength="6" placeholder="请输入手机动态码" v-model="formData.mobileDynacode" />
				<button type="primary" class="dynacode" @click="sendDynaCode('mobile')">{{ formData.mobileCodeText }}</button>
			</view>
			<view class="info-list-cell log-out-btn" @click="save('mobile')"><text class="cell-tit ns-text-color">保存</text></view>
		</view>
		<!-- 修改邮箱 -->
		<view v-if="indent == 'mailBox'" class="edit-info">
			<view class="edit-info-box">
				<text class="info-name">邮箱</text>
				<input class="uni-input info-content" type="email" maxlength="20" placeholder="请输入邮箱" v-model="formData.email" />
			</view>
			<view class="edit-info-box">
				<text class="info-name">验证码</text>
				<input class="uni-input info-content" type="number" maxlength="4" placeholder="请输入验证码" v-model="formData.emailVercode" />
				<view class="vercode"><imgcode width="80" height="22" ref="imgcode"></imgcode></view>
			</view>
			<view class="edit-info-box">
				<text class="info-name">动态码</text>
				<input class="uni-input info-content" type="number" maxlength="6" placeholder="请输入邮箱动态码" v-model="formData.emailDynacode" />
				<button type="primary" class="dynacode" @click="sendDynaCode('email')">{{ formData.emailCodeText }}</button>
			</view>
			<view class="info-list-cell log-out-btn" @click="save('email')"><text class="cell-tit ns-text-color">保存</text></view>
		</view>
	</view>
</template>

<script>
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
import imgcode from 'components/imgcode/imgcode.vue';
import validate from 'common/js/validate.js';
import http from 'common/js/http.js';
let than;
export default {
	components: {
		imgcode,
		uniNavBar
	},
	data() {
		return {
			formData: {
				userHeadImg: '',
				number: '', //账号
				nickName: '', //昵称
				currentPassword: '', //当前密码
				newPassword: '', //新密码
				confirmPassword: '', //确认密码
				mobile: '', //手机号
				mobileVercode: '', //手机验证码
				mobileDynacode: '', //手机动态验证吗
				mobileCodeText: '获取动态码',
				email: '', //邮箱
				emailVercode: '', //邮箱验证码
				emailDynacode: '', //邮箱动态验证码
				emailCodeText: '获取动态码'
			},
			memberInfo: {},
			indent: 'all',
			seconds: 120,
			timer: null,
			isSend: false,
			customNavTitle: '个人信息'
		};
	},
	onShow() {
		/* 初始化用户信息 */
		this.inintPersonalInfo();
		than = this;
	},
	mixins: [http],
	methods: {
		/**
		 * 初始化用户信息
		 */
		inintPersonalInfo() {
			this.sendRequest({
				url: 'System.Member.memberInfo',
				success: res => {
					if (res.code == 0) {
						this.memberInfo = res.data.user_info;
						this.formData.userHeadImg = this.memberInfo.user_headimg;
						this.formData.number = this.memberInfo.user_name; //账号
						this.formData.nickName = this.memberInfo.nick_name; //昵称
						this.formData.mobile = this.memberInfo.user_tel; //手机号
						this.formData.email = this.memberInfo.user_email; //邮箱
					}
				}
			});
		},
		/**
		 * 点击切换
		 */
		modifyInfo(type) {
			this.indent = type;
			if (type == 'name') {
				this.customNavTitle = '修改昵称';
			}
			if (type == 'password') {
				this.customNavTitle = '修改密码';
			}
			if (type == 'mobile') {
				this.customNavTitle = '绑定手机';
			}
			if (type == 'mailBox') {
				this.customNavTitle = '绑定邮箱';
			}
		},
		/**
		 * 导航返回
		 */
		NavReturn() {
			if (this.indent == 'all') {
				this.$util.redirectTo('/pages/member/index/index', '', 'tabbar');
			} else {
				this.$util.redirectTo('/pages/member/info/info');
			}
		},
		//修改昵称
		modifyNickName() {
			var rule = [{ name: 'nickName', checkType: 'required', errorMsg: '昵称不能为空' }];
			if (this.formData.nickName == this.memberInfo.nick_name) {
				this.$util.showToast({ title: '与原昵称一致，无需修改' });
				return;
			}

			if (!rule.length) return;
			var checkRes = validate.check(this.formData, rule);

			if (checkRes) {
				this.sendRequest({
					url: 'System.Member.modifynickname',
					data: { nickname: this.formData.nickName },
					success: res => {
						if (res.data > 0) {
							this.$util.showToast({ title: '修改成功' });
							setTimeout(() => {
								this.$util.redirectTo('/pages/member/info/info');
							}, 1000);
						} else {
							this.$util.showToast({ title: '修改失败' });
						}
					}
				});
			} else {
				this.$util.showToast({ title: validate.error });
			}
		},
		//修改密码
		modifyPassword() {
			var rule = [
				{ name: 'currentPassword', checkType: 'required', errorMsg: '请输入原始密码' },
				{ name: 'newPassword', checkType: 'required', errorMsg: '请输入新密码' },
				{ name: 'newPassword', checkType: 'lengthMin', checkRule: 6, errorMsg: '密码长度不能小于6位' }
			];
			if (this.formData.newPassword != this.formData.confirmPassword) {
				this.$util.showToast({ title: '两次密码不一致' });
				return;
			}

			if (!rule.length) return;
			var checkRes = validate.check(this.formData, rule);

			if (checkRes) {
				this.sendRequest({
					url: 'System.Member.modifyPassword',
					data: { new_password: this.formData.newPassword, old_password: this.formData.currentPassword },
					success: res => {
						if (res.data > 0) {
							this.$util.showToast({ title: '修改成功' });
							setTimeout(() => {
								this.$util.redirectTo('/pages/member/info/info');
							}, 1000);
						} else {
							this.$util.showToast({ title: res.data[1]});
						}
					}
				});
			} else {
				this.$util.showToast({ title: validate.error });
			}
		},
		//修改手机号
		async modifyMobile() {
			var test = await this.testBinding('mobile');
			if (!test) return;
			var mobileRule = [
				{ name: 'mobileVercode', checkType: 'required', errorMsg: '请输入验证码' },
				{
					name: 'mobileVercode',
					checkType: 'custom',
					errorMsg: '验证码错误',
					validate(value) {
						return than.$refs.imgcode.checkCode(value);
					}
				},
				{ name: 'mobileDynacode', checkType: 'required', errorMsg: '请输入动态码' }
			];
			var checkRes = validate.check(this.formData, mobileRule);
			if (checkRes) {
				this.sendRequest({
					url: 'System.Member.modifyMobileAPI',
					data: {
						account: this.formData.mobile,
						record_id: uni.getStorageSync('info_token'),
						code: this.formData.mobileDynacode,
						type: 'mobile'
					},
					success: res => {
						if (res.data > 0) {
							uni.removeStorage({ key: 'info_token' });
							this.isSend = false;
							this.$util.showToast({ title: '修改成功' });
							setTimeout(() => {
								this.$util.redirectTo('/pages/member/info/info');
							}, 1000);
						} else {
							this.$util.showToast({ title: res.message });
						}
					}
				});
			} else {
				this.$util.showToast({ title: validate.error });
			}
		},
		//修改邮箱
		async modifyEmail() {
			var test = await this.testBinding('email');
			if (!test) return;
			var emailRule = [
				{ name: 'emailVercode', checkType: 'required', errorMsg: '请输入验证码' },
				{
					name: 'emailVercode',
					checkType: 'custom',
					errorMsg: '验证码错误',
					validate(value) {
						return than.$refs.imgcode.checkCode(value);
					}
				},
				{ name: 'emailDynacode', checkType: 'required', errorMsg: '请输入动态码' }
			];
			var checkRes = validate.check(this.formData, emailRule);

			if (checkRes) {
				this.sendRequest({
					url: 'System.Member.modifyemailAPI',
					data: {
						account: this.formData.email,
						record_id: uni.getStorageSync('info_token'),
						code: this.formData.emailDynacode,
						type: 'email'
					},
					success: res => {
						if (res.data > 0) {
							uni.removeStorage({ key: 'info_token' });
							this.isSend = false;
							this.$util.showToast({ title: '修改成功' });
							setTimeout(() => {
								this.$util.redirectTo('/pages/member/info/info');
							}, 1000);
						} else {
							this.$util.showToast({ title: res.message });
						}
					}
				});
			} else {
				this.$util.showToast({ title: validate.error });
			}
		},

		/**
		 * 保存
		 */
		async save(type) {
			switch (type) {
				case 'name':
					this.modifyNickName();
					break;
				case 'password':
					this.modifyPassword();
					break;
				case 'mobile':
					this.modifyMobile();
					break;
				case 'email':
					this.modifyEmail();
					break;
			}
		},
		/**
		 * 检测手机或邮箱是否已绑定
		 */
		async testBinding(type) {
			var res = true;
			if (type == 'email') {
				res = await this.checkEmail();
			} else if (type == 'mobile') {
				res = await this.checkMobile();
			}
			return res;
		},
		//检测邮箱是否存在
		async checkEmail() {
			if (!this.vertifyEmail()) return false;
			let res = await this.sendRequest({
				url: 'System.Member.checkEmail',
				data: { email: this.formData.email },
				async: false
			});
			if (res.data) {
				this.$util.showToast({ title: res.message });
				return false;
			}
			return true;
		},
		async checkMobile() {
			if (!this.vertifyMobile()) return;
			let res = await this.sendRequest({
				url: 'System.Member.checkMobile',
				data: { mobile: this.formData.mobile },
				async: false
			});

			if (res.data) {
				this.$util.showToast({ title: res.message });
				return false;
			}
			return true;
		},
		/**
		 * 验证手机号
		 */
		vertifyMobile() {
			var rule = [{ name: 'mobile', checkType: 'required', errorMsg: '请输入手机号' }, { name: 'mobile', checkType: 'phoneno', errorMsg: '请输入正确的手机号' }];
			var checkRes = validate.check(this.formData, rule);
			if (!checkRes) {
				this.$util.showToast({ title: validate.error });
				return false;
			}
			return true;
		},
		/**
		 * 验证邮箱号
		 */
		vertifyEmail() {
			var rule = [{ name: 'email', checkType: 'required', errorMsg: '请输入邮箱号' }, { name: 'email', checkType: 'email', errorMsg: '请输入正确的邮箱号' }];
			var checkRes = validate.check(this.formData, rule);
			if (!checkRes) {
				this.$util.showToast({ title: validate.error });
				return false;
			}
			return true;
		},
		/**
		 * 发送动态码
		 */
		async sendDynaCode(parameterType) {
			var test = await this.testBinding(parameterType);
			if (!test) return;
			if (this.seconds != 120) return;
			var type, //发送动态码类型
				account, //动态码
				checkRes,
				key,
				rule = [];
			if (parameterType == 'mobile') {
				type = 'sms';
				key = 'bind_mobile';
				account = this.formData.mobile;
				rule = [
					{ name: 'mobile', checkType: 'required', errorMsg: '请输入手机号' },
					{ name: 'mobile', checkType: 'phoneno', errorMsg: '请输入正确的手机号' },
					{ name: 'mobileVercode', checkType: 'required', errorMsg: '请输入验证码' },
					{
						name: 'mobileVercode',
						checkType: 'custom',
						errorMsg: '验证码错误',
						validate(value) {
							return than.$refs.imgcode.checkCode(value);
						}
					}
				];
			} else if (parameterType == 'email') {
				type = 'email';
				account = this.formData.email;
				key = 'bind_email';
				rule = [
					{ name: 'email', checkType: 'required', errorMsg: '请输入邮箱号' },
					{ name: 'email', checkType: 'email', errorMsg: '请输入正确的邮箱号' },
					{ name: 'emailVercode', checkType: 'required', errorMsg: '请输入验证码' },
					{
						name: 'emailVercode',
						checkType: 'custom',
						errorMsg: '验证码错误',
						validate(value) {
							return than.$refs.imgcode.checkCode(value);
						}
					}
				];
			}

			checkRes = validate.check(this.formData, rule);

			if (checkRes && !this.isSend) {
				this.isSend = true;
				this.sendRequest({
					url: 'System.Send.sendDynamicCode',
					data: {
						account,
						type,
						key
					},
					success: res => {
						if (res.code == 0) {
							if (this.seconds == 120 && this.timer == null) {
								this.timer = setInterval(() => {
									this.seconds--;
									if (parameterType == 'mobile') {
										this.formData.mobileCodeText = '已发送(' + this.seconds + 'S)';
									} else if (parameterType == 'email') {
										this.formData.emailCodeText = '已发送(' + this.seconds + 'S)';
									}
								}, 1000);
							}
							uni.setStorageSync('info_token', res.data.record_id);
						} else {
							this.$util.showToast({ title: res.message });
							this.isSend = false;
						}
					}
				});
			} else {
				this.$util.showToast({ title: validate.error ? validate.error : '请勿重复点击' });
			}
		},
		/**
		 * 退出登录
		 */
		logout() {
			uni.removeStorage({
				key: 'token',
				success: res => {
					this.$util.redirectTo('/pages/member/index/index',{},'tabbar','redirectTo');
				}
			});
		}
	},
	watch: {
		seconds(value) {
			if (value == 0) {
				this.seconds = 120;
				this.formData.mobileCodeText = '获取动态码';
				this.formData.emailCodeText = '获取动态码';
				this.isSend = false;
				clearInterval(this.timer);
			}
		}
	},
	onHide() {
		this.seconds = 120;
		this.formData.mobileCodeText = '获取动态码';
		this.formData.emailCodeText = '获取动态码';
		this.isSend = false;
		clearInterval(this.timer);
	}
};
</script>

<style lang="scss">
page {
	overflow: hidden;
}
.info-list-cell {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 40rpx;
	position: relative;
	line-height: 50rpx;
	background-color: #fff;
	&.log-out-btn {
		margin-top: 40rpx;
		.cell-tit {
			margin: auto;
		}
	}
	.info-list-head {
		border: 1px solid $ns-bg-color-gray;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}
	.info-list-head image {
		max-width: 100%;
		max-height: 100%;
	}
	&.m-t {
		margin-top: 16rpx;
	}
	&.b-b:after {
		content: '';
		position: absolute;
		left: 30rpx;
		right: 30rpx;
		bottom: 0;
		border-bottom: 1px solid $ns-bg-color-gray;
	}
	.cell-tip {
		margin-left: auto;
		color: #999;
		color: lighten($ns-text-color-gray, 10%);
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		max-width: 470rpx;
	}
	.cell-more {
		margin-left: 10rpx;
		width: 32rpx;
		height: 100%;
	}
	.cell-more:after {
		content: '';
		display: block;
		width: 12rpx;
		height: 12rpx;
		border: 2rpx solid darken($ns-bg-color-gray, 20%) {
			right-color: transparent;
			bottom-color: transparent;
		}
		transform: rotate(135deg);
	}
}
.edit-info-box {
	margin-top: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 40rpx;
	min-height: 50rpx;
	background-color: #fff;
	.info-name {
		width: 150rpx;
		font-size: $ns-font-size-base;
		text-align: left;
	}
	.info-content {
		&:first-of-type {
			width: auto !important;
		}
		margin-right: auto;
		width: 250rpx;
		font-size: $ns-font-size-base;
		padding:0;
	}
	.dynacode {
		margin: 0;
		padding: 0 10rpx;
		width: 250rpx;
		height: 60rpx;
		font-size: $ns-font-size-base;
		line-height: 60rpx;
		color: #fff;
		word-break: break-all;
	}
}
.input-len {
	width: 500rpx !important;
}
</style>
